#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from django.utils import simplejson

from model import ClassState
from model import Question
from model import Lecture

class MyHandler(webapp.RequestHandler):
    
    def get(self):
        lectureKey = self.request.get('lectureKey')
        lecture = Lecture.get(lectureKey)
        
        classStates=db.Query(ClassState).filter('lecture =', lecture).fetch(limit=1)
        if len(classStates)==0:
            self.response.out.write("no class state")
            return
        

        classState = classStates[0]

        # db.delete(classState)
        
        action = self.request.get('action')
        questionKey = self.request.get('questionKey')
        question = Question.get(questionKey)

        if action=="Launch":
            classState.isQuizOn = True
            classState.quizQuestion = question
            
        if action=="Stop":
            classState.isQuizOn = False
            classState.quizQuestion = None

        classState.put()
            
        self.response.out.write(simplejson.dumps(True))

        # action = self.request.get('action')
        # questInd = int(self.request.get('questionIndex'))
        
        # output=False
        # message="ERROR"
        
        # if action=="Launch":
        #     output=True
        #     if newState.isQuizOn==True:
        #         message="Quiz is ON"
        #     else:
        #         # turn quiz on
        #         newState.isQuizOn=True
        #         newState.quizQuestionIndex=questInd
        #         newState.put()
        #         message="Quiz Launched"
        
        # if action=="Stop":
        #     output=True
        #     if newState.isQuizOn==False:
        #         message="Quiz is OFF"
        #     else:
        #         # turn quiz off
        #         newState.isQuizOn=False
        #         newState.put()
        #         message="Quiz Stopped"
       
        # if output==False:
        #     message="Unknown action, Please try another"
            
        # dirResponse=dict(success=output,message=message)
        # self.response.out.write(json.dumps(dirResponse))
        
              
def main():
    app = webapp.WSGIApplication([
        (r'.*', MyHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()